package org.esisar.controller.user;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.esisar.exceptions.IncorrectCredentialsException;
import org.esisar.exceptions.UserExistException;

public class UserController extends HttpServlet {
	
	public void init(ServletConfig config) throws ServletException{
		super.init(config);
	}

	public void doGet(HttpServletRequest req, HttpServletResponse res) 
			throws ServletException, IOException{

		res.setContentType("text/html");

		if(req.getParameter("login") != null){
			
			try {
				UserUtils.login(req);
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (IncorrectCredentialsException e) {
				req.setAttribute("message", e.getMessage());
				req.getRequestDispatcher("User/login.jsp").forward(req, res);
				e.printStackTrace();
			}
			req.getRequestDispatcher("User/panel.jsp").forward(req, res);	
	
		}else if (req.getParameter("create") != null) {
			
			try {
				UserUtils.register(req);	
				req.getRequestDispatcher("User/login.jsp").forward(req, res);
				
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (UserExistException e) {
				req.setAttribute("message", "Mail already used");
				req.getRequestDispatcher("User/create.jsp").forward(req, res);
				e.printStackTrace();
			}
		}else if (req.getParameter("logout") != null){
			UserUtils.logout(req);
			req.getRequestDispatcher("index.jsp").forward(req, res);
			
			
		}
	}
}
